//入口文件
//引入sme-routre
import SMERouter from 'sme-router';
//引入一级路由视图文件
import loginView from '$v/login'
import advView from '$v/adv'
//引入二级路由视图文件
import advListView from '$v/advList'
import adminListView from '$v/adminList'

// 引入axios
import axios from 'axios'
import request from './util/request';
 

// 实例化路由对象
const router = new SMERouter("app", "html5")

window.router = router;
// 配置路由
router.route("/login", (req, res) => {
  res.render(loginView())
  // console.log(req,res);
  // req:请求路由对象,主要包含了请求路由地址 和 其他传参的参数
  // res:响应对象,主要包含响应方法,例:render方法,响应一个渲染

})


//配置adv,以及二级路由
router.route("/adv", (req, res, next) => {
  next(advView({
    subRoute: res.subRoute(),
    url: req.url
  }));
})


router.route("/adv/adminList", (req, res) => {
  res.render(adminListView());

  // 添加管理员功能,给保存按钮绑定点击事件
  const oSaveAdminBtn = document.querySelector('#saveAdminBtn');
  oSaveAdminBtn.onclick =async function () {
    // 获取相关元素　　.trim是去除前后空格
    const adminNameValue = document.adminForm.adminName.value.trim();
    const passwordValue = document.adminForm.password.value.trim();
    const rePasswordValue = document.adminForm.rePassword.value.trim();

    // 判断所有输入内容不能为空
    if (!adminNameValue || !passwordValue || !rePasswordValue) {
      return alert('输入内容不能为空')
    }
    // 判断密码是否一致
    if (passwordValue !== rePasswordValue) {
      return alert('联次输入密码不一致')
    }
    // 向后端发送添加管理员请求
    try {
     await request.post('/addAdmin', {
        adminName: adminNameValue,
        password: passwordValue,
        regTime: new Date().toLocaleString()
      })
      alert('添加成功');
    } catch (e) {
      alert('异常' + e.message)
    }

  }
})
router.route("/adv/advList", (req, res) => {
  res.render(advListView())
})


